﻿using DAL;
using IService;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Model;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WMS.Controllers
{
    public class NumberingRulesController : Controller
    {
        private readonly INumberingRuleService _numberingRuleService;
        private readonly ILogger<NumberingRulesController> _logger;
        private readonly AppDbContext _context;

        public NumberingRulesController(
            INumberingRuleService numberingRuleService,
            ILogger<NumberingRulesController> logger,
            AppDbContext context)
        {
            _numberingRuleService = numberingRuleService;
            _logger = logger;
            _context = context;
        }

        #region 基础操作（仅基于规则ID）
        // 列表查询（支持按RuleId筛选，适配修改后的Service方法）
        public async Task<IActionResult> Index(
            long? ruleId,
            string numberPrefix,
            string operateTime,
            string timeRule)
        {
            DateTime? startTime = null;
            DateTime? endTime = null;

            // 时间解析逻辑保持不变
            if (!string.IsNullOrEmpty(operateTime) && operateTime != "请选择")
            {
                if (operateTime.Contains("-"))
                {
                    var dateParts = operateTime.Split(new string[] { " - " }, StringSplitOptions.RemoveEmptyEntries);
                    if (dateParts.Length == 2)
                    {
                        DateTime.TryParseExact(dateParts[0].Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime startDate);
                        DateTime.TryParseExact(dateParts[1].Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime endDate);
                        startTime = startDate;
                        endTime = endDate.Date.AddDays(1).AddSeconds(-1);
                    }
                }
                else
                {
                    if (DateTime.TryParseExact(operateTime, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime singleDate))
                    {
                        startTime = singleDate.Date;
                        endTime = singleDate.Date.AddDays(1).AddSeconds(-1);
                    }
                }
            }

            try
            {
                // 调用修改后的Query方法，传入RuleId等参数
                var rules = await _numberingRuleService.QueryNumberingRulesAsync(
                    ruleId: ruleId,
                    prefix: numberPrefix,
                    startTime: startTime,
                    endTime: endTime,
                    timeRule: timeRule);
                return View(rules);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询编号规则列表失败");
                TempData["ErrorMessage"] = "加载数据失败，请稍后重试";
                return View(new List<NumberingRule>());
            }
        }

        // 编辑规则（仅按ID）
        public async Task<IActionResult> Edit(long? id)
        {
            if (id == null)
                return NotFound("规则ID不能为空");

            try
            {
                var rule = await _numberingRuleService.GetNumberingRuleByIdAsync(id.Value);
                if (rule == null)
                    return NotFound($"未找到ID为{id}的规则");

                // 生成预览编号
                string previewNumber;
                try
                {
                    previewNumber = await _numberingRuleService.GenerateNumberByRuleIdAsync(id.Value);
                }
                catch (Exception ex)
                {
                    _logger.LogWarning(ex, "生成预览编号失败，使用备用方法");
                    previewNumber = GeneratePreview(rule);
                }

                ViewBag.GenerateRulePreview = previewNumber ?? "预览生成失败";
                return PartialView("Edit", rule);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载ID为{Id}的编号规则失败", id);
                return Json(new { success = false, message = "加载数据失败，请稍后重试" });
            }
        }

        // 保存编辑（仅按ID）
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit([FromForm] NumberingRule rule)
        {
            if (rule.RuleId <= 0)
                return Json(new { success = false, message = "规则ID无效" });

            // 保留创建信息，仅更新必要字段
            var existingRule = await _numberingRuleService.GetNumberingRuleByIdAsync(rule.RuleId);
            if (existingRule != null)
            {
                rule.CreateBy = existingRule.CreateBy;
                rule.CreateTime = existingRule.CreateTime;
            }
            rule.UpdateBy = "admin";
            rule.UpdateTime = DateTime.Now;
            rule.IsDelete = "0";
            rule.TargetForm = null; // 强制清空

            try
            {
                await _numberingRuleService.UpdateNumberingRuleAsync(rule);
                return Json(new { success = true, message = "保存成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存失败，RuleId: {RuleId}", rule.RuleId);
                return Json(new { success = false, message = ex.Message });
            }
        }

        // 生成预览编号（公共调用，仅按ID）
        [HttpPost]
        public async Task<IActionResult> GenerateByRuleId(long ruleId)
        {
            try
            {
                if (ruleId <= 0)
                    return Json(new { success = false, message = "规则ID无效" });

                var number = await _numberingRuleService.GenerateNumberByRuleIdAsync(ruleId);
                return Json(new { success = true, number = number, message = "预览编号生成成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成预览编号失败，RuleId: {RuleId}", ruleId);
                return Json(new { success = false, message = ex.Message });
            }
        }

        // 生成编号并更新最大值（核心：进货单调用此接口）
        [HttpPost]
        public async Task<IActionResult> GenerateAndUpdateNumber(long ruleId)
        {
            try
            {
                if (ruleId <= 0)
                    return Json(new { success = false, message = "规则ID无效" });

                var number = await _numberingRuleService.GenerateAndUpdateNumberAsync(ruleId);
                return Json(new { success = true, number = number, message = "编号生成成功并更新最大值" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成编号失败，RuleId: {RuleId}", ruleId);
                return Json(new { success = false, message = ex.Message });
            }
        }

        // 手动更新最大值（仅按ID）
        [HttpPost]
        public async Task<IActionResult> UpdateMaxAfterSuccessById(long ruleId, int currentSerial)
        {
            try
            {
                if (ruleId <= 0 || currentSerial < 0)
                    return Json(new { success = false, message = "参数无效" });

                await _numberingRuleService.UpdateMaxValueAfterSuccessAsync(ruleId, currentSerial);
                return Json(new { success = true, message = "最大值更新成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新最大值失败，RuleId: {RuleId}", ruleId);
                return Json(new { success = false, message = ex.Message });
            }
        }

        // 重置规则（仅按ID）
        [HttpPost]
        public async Task<IActionResult> ResetNumberingRule(long ruleId)
        {
            try
            {
                await _numberingRuleService.ResetNumberingRuleAsync(ruleId);
                return Json(new { success = true, message = "重置成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "重置失败，RuleId: {RuleId}", ruleId);
                return Json(new { success = false, message = ex.Message });
            }
        }

        // 重置所有过期规则（定时任务）
        [HttpPost]
        public async Task<IActionResult> ResetAllExpiredRules()
        {
            try
            {
                await _numberingRuleService.ResetAllExpiredRulesAsync();
                return Json(new { success = true, message = "重置所有过期规则成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "重置所有过期规则失败");
                return Json(new { success = false, message = "系统异常，请联系管理员" });
            }
        }
        #endregion

        #region 新增/删除/导出（仅基于ID）
        // 导出Excel（支持按RuleId筛选）
        [HttpGet]
        public async Task<IActionResult> Export(
            long? ruleId,
            string numberPrefix,
            string operateTime,
            string selectedIds,
            string timeRule)
        {
            try
            {
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                List<NumberingRule> rules;

                // 优先按选中ID列表导出
                if (!string.IsNullOrEmpty(selectedIds))
                {
                    var ids = selectedIds.Split(',').Select(long.Parse).ToList();
                    rules = await _numberingRuleService.GetNumberingRulesByIdsAsync(ids);
                }
                // 其次按单个RuleId导出
                else if (ruleId.HasValue && ruleId > 0)
                {
                    var singleRule = await _numberingRuleService.GetNumberingRuleByIdAsync(ruleId.Value);
                    rules = singleRule != null ? new List<NumberingRule> { singleRule } : new List<NumberingRule>();
                }
                // 最后按条件导出
                else
                {
                    DateTime? startTime = null;
                    DateTime? endTime = null;
                    if (!string.IsNullOrEmpty(operateTime) && operateTime != "请选择")
                    {
                        if (operateTime.Contains("-"))
                        {
                            var dateParts = operateTime.Split(new string[] { " - " }, StringSplitOptions.RemoveEmptyEntries);
                            if (dateParts.Length == 2)
                            {
                                DateTime.TryParseExact(dateParts[0].Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime startDate);
                                DateTime.TryParseExact(dateParts[1].Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime endDate);
                                startTime = startDate;
                                endTime = endDate.Date.AddDays(1).AddSeconds(-1);
                            }
                        }
                    }

                    rules = await _numberingRuleService.QueryNumberingRulesAsync(
                        ruleId: ruleId,
                        prefix: numberPrefix,
                        startTime: startTime,
                        endTime: endTime,
                        timeRule: timeRule);
                }

                if (rules == null || !rules.Any())
                    return Content("<script>alert('没有可导出的数据'); window.close();</script>", "text/html");

                return GenerateExcelFile(rules);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出Excel失败");
                return Content($"<script>alert('导出失败：{ex.Message}'); window.close();</script>", "text/html");
            }
        }

        // 生成Excel文件（无目标表单列）
        private IActionResult GenerateExcelFile(List<NumberingRule> rules)
        {
            using (var package = new ExcelPackage())
            {
                var worksheet = package.Workbook.Worksheets.Add("编号规则列表");
                // 表头（无目标表单）
                worksheet.Cells[1, 1].Value = "序号";
                worksheet.Cells[1, 2].Value = "规则ID";
                worksheet.Cells[1, 3].Value = "编号前缀";
                worksheet.Cells[1, 4].Value = "时间规则";
                worksheet.Cells[1, 5].Value = "流水号位数";
                worksheet.Cells[1, 6].Value = "步长";
                worksheet.Cells[1, 7].Value = "当前最大值";
                worksheet.Cells[1, 8].Value = "编号生成规则";
                worksheet.Cells[1, 9].Value = "最后更新时间";

                // 表头样式
                using (var headerRange = worksheet.Cells[1, 1, 1, 9])
                {
                    headerRange.Style.Font.Bold = true;
                    headerRange.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                    headerRange.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    headerRange.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
                }

                // 填充数据
                for (int i = 0; i < rules.Count; i++)
                {
                    var rule = rules[i];
                    int row = i + 2;
                    worksheet.Cells[row, 1].Value = i + 1;
                    worksheet.Cells[row, 2].Value = rule.RuleId;
                    worksheet.Cells[row, 3].Value = rule.NumberPrefix;
                    worksheet.Cells[row, 4].Value = rule.TimeRule;
                    worksheet.Cells[row, 5].Value = rule.SerialNumberDigit;
                    worksheet.Cells[row, 6].Value = rule.Step;
                    worksheet.Cells[row, 7].Value = rule.MaxValue;
                    worksheet.Cells[row, 8].Value = rule.NumberGenerationRule;
                    worksheet.Cells[row, 9].Value = rule.LastUpdateTime.ToString("yyyy-MM-dd HH:mm:ss");
                }

                worksheet.Cells.AutoFitColumns(0);
                var stream = new MemoryStream();
                package.SaveAs(stream);
                stream.Position = 0;

                string fileName = $"编号规则_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
            }
        }

        // 新增规则页面
        public IActionResult Add()
        {
            return View();
        }

        // 创建规则（无目标表单）
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(NumberingRule model)
        {
            try
            {
                // 初始化参数
                model.TimeRule = Request.Form["SelectedTimeRule"].ToString() ?? "年月日";
                model.CreateBy = "admin";
                model.UpdateBy = "admin";
                model.CreateTime = DateTime.Now;
                model.UpdateTime = DateTime.Now;
                model.IsDelete = "0";
                model.MaxValue = 0;
                model.LastUpdateTime = DateTime.Now;
                model.TargetForm = null; // 强制清空

                // 生成编号规则字符串
                if (string.IsNullOrEmpty(model.NumberGenerationRule))
                    model.NumberGenerationRule = GenerateNumberRuleString(model);

                // 表单校验
                if (!ModelState.IsValid)
                {
                    ModelState.Remove("TimeRule");
                    if (!ModelState.IsValid)
                    {
                        var errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage);
                        return Json(new { success = false, message = "表单无效：" + string.Join("；", errors) });
                    }
                }

                await _numberingRuleService.AddNumberingRuleAsync(model);
                return Json(new { success = true, message = "新增成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "新增失败，前缀: {Prefix}", model?.NumberPrefix);
                return Json(new { success = false, message = ex.Message });
            }
        }

        // 生成编号规则字符串（无目标表单）
        private string GenerateNumberRuleString(NumberingRule model)
        {
            var ruleBuilder = new StringBuilder();
            ruleBuilder.Append(model.NumberPrefix ?? "");
            ruleBuilder.Append("YYYYMMDD");

            if (!int.TryParse(model.SerialNumberDigit, out int digitCount))
            {
                _logger.LogWarning("流水号位数无效，用默认3位");
                digitCount = 3;
            }
            ruleBuilder.Append(new string('0', digitCount));

            return ruleBuilder.ToString();
        }

        // 删除规则（仅按ID）
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Delete(long ruleId)
        {
            try
            {
                if (ruleId <= 0)
                    return Json(new { success = false, message = "规则ID无效" });

                await _numberingRuleService.DeleteNumberingRuleAsync(ruleId);
                return Json(new { success = true, message = "删除成功" });
            }
            catch (KeyNotFoundException ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除失败，RuleId: {RuleId}", ruleId);
                return Json(new { success = false, message = "系统异常" });
            }
        }
        #endregion

        // 备用预览方法（无目标表单）
        private string GeneratePreview(NumberingRule rule)
        {
            if (rule == null)
                return "预览失败";

            try
            {
                string datePart = DateTime.Now.ToString("yyyyMMdd");
                int nextSerial = rule.MaxValue + rule.Step;
                int digitCount = int.TryParse(rule.SerialNumberDigit, out int digit) ? digit : 3;
                string serial = nextSerial.ToString().PadLeft(digitCount, '0');
                return $"{rule.NumberPrefix}{datePart}{serial}";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "备用预览失败，RuleId: {RuleId}", rule.RuleId);
                return "预览失败";
            }
        }
    }
}